package com.chidopi.market.bookstore.actions;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.io.IOUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.chidopi.cdf.exception.CdfException;
import com.chidopi.cdf.service.IBaseService;
import com.chidopi.cdf.service.ICommonService;
import com.chidopi.cdf.struts1actions.StandardOperatorAction;
import com.chidopi.cdf.util.ModelContextFactory;
import com.chidopi.market.aa.service.ICityPermissionService;
import com.chidopi.market.bookstore.domain.Book2City;
import com.chidopi.market.bookstore.domain.BookCategories;
import com.chidopi.market.bookstore.domain.BookItems;
import com.chidopi.market.bookstore.domain.BookLang;
import com.chidopi.market.bookstore.domain.ProductID2Book;
import com.chidopi.market.bookstore.service.IBookItemsService;
import com.chidopi.market.bookstore.service.IResourceService;
import com.chidopi.market.util.FileHelper;
import com.chidopi.market.util.MessageHandler;

public class BookItemsAction extends StandardOperatorAction<BookItems>{
	
	private String RES_PATH = "";
	
	private static Logger logger = LoggerFactory.getLogger(BookItemsAction.class);
	
	private IBookItemsService baseService;
	
	private IResourceService resourceService;
	
	private IBaseService<ProductID2Book> pbService;
	
	private ICityPermissionService cityPService;
	
	private IBaseService<Book2City> b2cService;
		
	private ICommonService commonService;
	public BookItemsAction(){
	    this("");	
	}
	
	@SuppressWarnings("unchecked")
	public BookItemsAction(String entryURL) {
		this.entryURL = entryURL;
		
		try {
			this.baseService = (IBookItemsService)
				ModelContextFactory.get("bookItemsService", IBaseService.class);
		} catch (Exception e) {
			this.baseService = null;
			logger.warn("initial IBookItemsService", e);
		}
		
		try{
			this.resourceService = (IResourceService)
			    ModelContextFactory.get("resourceService", IResourceService.class);
			logger.debug("Path: " + resourceService.getBookCityResPath());
			this.RES_PATH = resourceService.getBookCityResPath();
		}catch(Exception e){
			this.resourceService = null;
			logger.warn("initial IResourceService", e);
		}
		
		try {
			this.pbService = (IBaseService<ProductID2Book>)
				ModelContextFactory.get("productID2BookService", IBaseService.class);
		} catch (Exception e) {
			this.pbService = null;
			logger.warn("initial productID2BookService", e);
		}
		
		try {
			this.cityPService = 
				ModelContextFactory.getT("cityPermissionService", ICityPermissionService.class);
		} catch (Exception e) {
			this.cityPService = null;
			logger.warn("initial productID2BookService", e);
		}

		try {
			this.b2cService = (IBaseService<Book2City>)
				ModelContextFactory.get("book2cityService", IBaseService.class);
		} catch (Exception e) {
			this.b2cService = null;
			logger.warn("initial book2cityService", e);
		}
		
		try {
			this.commonService = 
				ModelContextFactory.getT("commonService", ICommonService.class);
		} catch (Exception e) {
			this.cityPService = null;
			logger.warn("initial productID2BookService", e);
		}

	}
	
	public ActionForward init(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String uri = request.getRequestURI();
		String funcUri = uri.substring(uri.lastIndexOf('/') + 1);
		logger.debug("init) {}", funcUri);
		request.getSession().setAttribute("funcurl", funcUri);
		this.entryURL = "/" + funcUri;
		DynaBean dynaForm = (DynaBean) form;
		dynaForm.set("vo", null);
		dynaForm.set("op", null);
		return mapping.findForward("success");
	}
	
	public ActionForward back(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		return mapping.findForward("success");
	}
	

	// 分類查詢
	private static final String[] conditions = {"id", "bookname", "description","album_flag","enable_flag", "keyword", "release_date", "code", "description"};
	public ActionForward query(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (null == this.baseService) return mapping.findForward("error");
		Integer userId = (Integer) request.getSession().getAttribute("user_id");
		int city_id = this.cityPService.getCityPermission(userId, (String) request.getSession().getAttribute("funcurl"));

		StringBuffer sql = new StringBuffer();
		ArrayList<String> args = new ArrayList<String>();
		for (String cond : conditions) {
			
			String value = (String) request.getParameter(cond);
			if (value == null || value.trim().equals("")) continue;
			logger.debug(cond + "=" + value);
			
			if(cond.endsWith("_flag") && request.getParameterValues(cond).length >1){
				 continue;
			}

			if (sql.length() > 1) sql.append("and ");
			if(cond.endsWith("_flag")){
				sql.append(cond + " = ? ");
				args.add( value );
			}else if (cond.equals("release_date")){
				sql.append("DATE_FORMAT(" + cond + ", '%Y-%m-%d') = DATE_FORMAT( ? ,'%Y-%m-%d') ");
				args.add( value );
			}else {
				sql.append(cond + " like ?");
				args.add("%" + value +"%");
			}
		}
		if (city_id > 0) {
			if (sql.length() > 0) sql.append(" and");
			sql.append(" id in (select book_id from book2city where city_id=" + city_id + ") ");
		}
		logger.debug("where=" + sql.toString());
		List<BookItems> list = this.baseService.find(sql.toString(),args.toArray());
		logger.debug("size=" + list.size());
		JSONArray json = JSONArray.fromObject(list);
		PrintWriter out=response.getWriter();
		// logger.debug(json.toString());
        out.println(json);
        out.flush();
		return null;
	}
	
	private ActionForward switchForward(ActionMapping mapping, HttpServletRequest request) {
		Integer userId = (Integer) request.getSession().getAttribute("user_id");
		int city_id = this.cityPService.getCityPermission(userId, (String) request.getSession().getAttribute("funcurl"));
		if (city_id > 0) return mapping.findForward("city_success");
		return mapping.findForward("success");
	}
	
	private void findById(HttpServletRequest request, BookItems t) throws Exception {
		Integer userId = (Integer) request.getSession().getAttribute("user_id");
		int city_id = this.cityPService.getCityPermission(userId, (String) request.getSession().getAttribute("funcurl"));
		if (city_id > 0) {
			List<Book2City> bok2cits = this.b2cService.find("book_id=? and city_id=?", new Integer(request.getParameter("id")), city_id);
			if (bok2cits != null && bok2cits.size() > 0) {
				t.setSale_price(bok2cits.get(0).getSale_price());
				t.setSubscribe_quota(bok2cits.get(0).getSubscribe_quota());
				String msg = String.format("%s@%d 's price=%f, quota=%d", request.getParameter("id"), city_id,
						bok2cits.get(0).getSale_price(), bok2cits.get(0).getSubscribe_quota());
				logger.info(msg);
			} else {
				logger.warn("{}@{} has no sale_price and quota", request.getParameter("id"), city_id);
			}
		}
	}
	
	public ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String id = request.getParameter("id");
		logger.debug("id=" + id);
		BookItems t = this.baseService.findById(new Integer(id));
		if (null == t) {
			logger.warn("BookItems[id={}] is deleted!!", id);
			return mapping.findForward("err");
		}
		this.findById(request, t);
		DynaBean dynaForm = (DynaBean) form;
		dynaForm.set("op", "delete");
		dynaForm.set("vo", t);
		List<BookLang>langs = t.getBookLangs();
		if(null != langs){
			for(BookLang lang : langs){
				dynaForm.set(lang.getLang(), lang.getBookname());
			}
		}
				
		List<BookCategories> categories = this.baseService.findAllCategories();
		dynaForm.set("categories", categories);
		
		List<BookItems> books = this.baseService.findAllSingleBooks();
		dynaForm.set("books", books);
		
		return this.switchForward(mapping, request);
	}

	public ActionForward insert(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String id = request.getParameter("id");
		logger.debug("id=" + id);
		BookItems t = this.baseService.findById(id);
		if (null == t) t = new BookItems();
		else this.findById(request, t);
		DynaBean dynaForm = (DynaBean) form;
		dynaForm.set("op", "insert");
		dynaForm.set("vo", t);
		
		List<BookLang>langs = t.getBookLangs();
		if(null != langs){
			for(BookLang lang : langs){
				dynaForm.set(lang.getLang(), lang.getBookname());
			}
		}
		t.setAlbum_flag(null);
		t.setBooks(null);
		t.setIconImage(null);
		t.setThumbImage(null);
		t.setZipfile(null);
		t.setZipFileName(null);
		t.setBooksize(null);
		t.setKeyword(null);
		t.setRelease_date(null);
		
		List<BookCategories> categories = this.baseService.findAllCategories();
		dynaForm.set("categories", categories);
		
		List<BookItems> books = this.baseService.findAllSingleBooks();
		dynaForm.set("books", books);

		return this.switchForward(mapping, request);
	}

	public ActionForward update(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String id = request.getParameter("id");
		logger.debug("id=" + id);
		BookItems t = this.baseService.findById(id);
		if (null == t) {
			logger.warn("BookItems[id={}] is deleted!!", id);
			return mapping.findForward("err");
		}
		this.findById(request, t);
		DynaBean dynaForm = (DynaBean) form;
		dynaForm.set("op", "update");
		dynaForm.set("vo", t);
		List<BookLang>langs = t.getBookLangs();
		if(null != langs){
			for(BookLang lang : langs){
				dynaForm.set(lang.getLang(), lang.getBookname());
			}
		}
				
		List<BookCategories> categories = this.baseService.findAllCategories();
		dynaForm.set("categories", categories);
		
		List<BookItems> books = this.baseService.findAllSingleBooks();
		dynaForm.set("books", books);
		return this.switchForward(mapping, request);
	}
	
	private String genZip(FormFile pdf) throws Exception {
		String tmpPath = this.resourceService.getSysProp().getProperty("bookcity_tmp_path", "/root/tmp/");
		String pdfFile = tmpPath + pdf.getFileName();
		FileHelper.writeFile(pdf, pdfFile);
		String suffix = FileHelper.getFileSuffix(pdf.getFileName());
		
		File plist = new File(this.resourceService.getSysProp().getProperty(suffix + "_file"));

		String outputPath = tmpPath + pdf.getFileName().replaceFirst("." + suffix + "$", ".zip");
		ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(outputPath));
		zos.setLevel(1);
		String defaultFileName = pdf.getFileName();
		if (!suffix.equals("zip")) {
			defaultFileName = this.resourceService.getSysProp().getProperty("default_" + suffix + "_name", defaultFileName);
			logger.debug("default name:{}", defaultFileName);
		}
		ZipEntry ze = new ZipEntry(defaultFileName);
		FileInputStream fis = new FileInputStream(pdfFile);
		
		zos.putNextEntry(ze);
		IOUtils.copy(fis, zos);
		zos.closeEntry();
		
		ZipEntry zePlist = new ZipEntry("Medialist.plist");
		FileInputStream fisPlist = new FileInputStream(plist);
		zos.putNextEntry(zePlist);
		IOUtils.copy(fisPlist, zos);
		zos.closeEntry();
		zos.close();
		File srcFile = new File(pdfFile);
		srcFile.delete();
		return outputPath;
	}

	public ActionForward save(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String op = request.getParameter("op");
		Integer userId = (Integer) request.getSession().getAttribute("user_id");
		int city_id = this.cityPService.getCityPermission(userId, (String) request.getSession().getAttribute("funcurl"));
		
		logger.debug("op=" + op);
		if("delete".equals(op))
		      return remove(mapping, form, request, response);
		
		BookItems t = new BookItems();
		logger.debug("BookLang: ====" + request.getParameter("vo.bookLangs"));
		DynaBean dynaForm = (DynaBean) form;
		try {			
			PropertyUtils.copyProperties(t, dynaForm.get("vo"));
			logger.debug(t.getId() + ":" + t.getBookname() + "/" + t.getBookLangs());
		} catch (Exception e) {
			logger.warn("PropertyUtils", e);
			return mapping.findForward("err");
		}
		
	    String oldIcon = "";
	    String oldThumb = "";

	    // two images path save to res folder
	    FormFile icon = (FormFile) dynaForm.get("icon");
	    logger.debug("icon size: " + icon.getFileSize());
	    if(icon != null && icon.getFileSize() > 0){
		    String suffix = FileHelper.getFileSuffix(icon.getFileName());
		    String iconName =  FileHelper.getRandomTimeString("icon" ) + (suffix.length() > 0 ? "." + suffix : suffix);
		    oldIcon = t.getIconImage();
		    t.setIconImage(iconName);
	    }	    
	    FormFile thumb = (FormFile)dynaForm.get("thumb");
	    if(thumb != null && thumb.getFileSize() > 0){
	    	String suffix = FileHelper.getFileSuffix(thumb.getFileName());
	    	String thumbName =  FileHelper.getRandomTimeString("thumb" ) + (suffix.length() > 0 ? "." + suffix : suffix); 
	    	oldThumb = t.getThumbImage();
		    t.setThumbImage(thumbName);
	    }
	    
	    // album setting
	    FormFile zip = null;
	    String filePath = null;
	   	String album = t.getAlbum_flag();
	   	logger.debug("album: " + album);
	   	if("Y".equals(album)){
	   		String [] bookItems = request.getParameterValues("vo.books");
		    if(bookItems != null){
		    	logger.debug("bookItmes.size : " + bookItems.length);
		    	List<BookItems> items  = new ArrayList<BookItems>();
		    	for(String book: bookItems){
		    		BookItems item = new BookItems();
		    		item.setId(Integer.parseInt(book));
		    		items.add(item);
		    	}
		    	t.setBooks(items);
		    }
	   	}else{
	   		t.setAlbum_flag("N");
	   		// zip file path save to res folder
	   		zip = (FormFile)dynaForm.get("zipfile");
	   		filePath = t.getFilepath();
	   		if(zip != null && zip.getFileSize() > 0){
	   			String suffix = FileHelper.getFileSuffix(zip.getFileName());
	   			if (!suffix.endsWith("zip")) {
		   			String suffixPath = this.resourceService.getSysProp().getProperty(suffix + "_file");
					if (suffixPath == null) {
						logger.warn("{} don't be defined in properties", suffix);
						return mapping.findForward("err");
					} else {
						File plist = new File(suffixPath);
						if (!plist.exists()) {
							logger.warn("{} don't be ready!!", suffix);
							return mapping.findForward("err");
						}
					}
	   			}
	   			String zipName =  FileHelper.getRandomTimeString("book" ) + (suffix.length() > 0 ? "." + suffix : suffix); 

	   			t.setOldfile(t.getZipfile());
	   			t.setZipfile(zipName);
	   			t.setOldfilename(t.getZipFileName());
	   			t.setZipFileName(zip.getFileName());
	   			t.setBooksize(zip.getFileSize() / 1024); // change to KB	   			
	   		} else if (filePath != null) {				// 1/3 指定URL copy素材
	   			File f = new File(filePath);
	   			if (f.exists()) {
	   				long size = f.length();
	   				String suffix = FileHelper.getFileSuffix(f.getName());
		   			if (!suffix.endsWith("zip")) {
			   			String suffixPath = this.resourceService.getSysProp().getProperty(suffix + "_file");
						if (suffixPath == null) {
							logger.warn("{} don't be defined in properties", suffix);
							return mapping.findForward("err");
						} else {
							File plist = new File(suffixPath);
							if (!plist.exists()) {
								logger.warn("{} don't be ready!!", suffix);
								return mapping.findForward("err");
							}
						}
		   			}
		   			String zipName =  FileHelper.getRandomTimeString("book" ) + (suffix.length() > 0 ? "." + suffix : suffix); 

		   			t.setOldfile(t.getZipfile());
		   			t.setZipfile(zipName);
		   			t.setOldfilename(t.getZipFileName());
		   			t.setZipFileName(f.getName());
		   			t.setBooksize((int)(size / 1024)); // change to KB
	   			} else {
	   				filePath = null;
	   			}
	   		}
	   	}
	   	
	    // langs setting
	   	String booknamecn = request.getParameter("zh_cn");
	   	String booknametw = request.getParameter("zh_tw");
	   	String booknameen = request.getParameter("en");
	   	
	   	List<BookLang> langs = new ArrayList<BookLang>();
	   	if(null != booknamecn && booknamecn.length()>0){
	   		BookLang lang = new BookLang();
	   		lang.setLang("zh_cn");
	   		lang.setBookname(booknamecn);
	   		langs.add(lang);
	   	}
	   	
	   	if(null != booknametw && booknametw.length() > 0){
	   		BookLang lang = new BookLang();
	   		lang.setLang("zh_tw");
	   		lang.setBookname(booknametw);
	   		langs.add(lang);
	   	}
	   	
	   	if(null != booknameen && booknameen.length() > 0){
	   		BookLang lang = new BookLang();
	   		lang.setLang("en");
	   		lang.setBookname(booknameen);
	   		langs.add(lang);
	   	}
	   	logger.debug("booklangs: " + langs.toString() + " " + t.getBookLangs());
	   	if( langs.isEmpty())
	   		t.setBookLangs(null);
	   	else
	   		t.setBookLangs(langs);
	   	
	    // categories setting
	    String [] categories = request.getParameterValues("vo.categories");
	    if(categories != null){
		    List<BookCategories> list = new ArrayList<BookCategories>();
		    for(String category: categories){
		    	BookCategories cat = new BookCategories();
		    	cat.setId(Integer.parseInt(category));
		    	list.add(cat);
		    }
		    t.setCategories(list);
	    }   
	    logger.debug("categories: ");
		int ret = -1;
		String dest = "";
		FileHelper.checkPath(RES_PATH);
		if ("insert".equals(op)) {
			t.setCreate_by(userId);
			String zipfilename = null;

			if (!t.getZipfile().endsWith(".zip")) {
				zipfilename = t.getZipfile().replaceFirst("\\.(pdf|swf)$", ".zip");
				logger.debug("{} -> {}", t.getZipfile(), zipfilename);
				t.setZipfile(zipfilename);
			} else {
				logger.debug("old name: {}", t.getZipfile());
			}
			ret = this.baseService.insert(t);
			if (ret > -1 && city_id > 0) {			
				Book2City b2c = new Book2City();
				b2c.setCity_id(city_id);
				b2c.setBook_id(t.getId());
				b2c.setSale_price(t.getSale_price());
				b2c.setSubscribe_quota(t.getSubscribe_quota());
				ret = this.b2cService.insert(b2c);
			}
			if(ret > -1){				
				// write iconImage to res folder 
				if( icon != null && icon.getFileSize() > 0 ){
					dest = RES_PATH + t.getIconImage();
					logger.debug("IconImage Path: " + dest);
					FileHelper.writeFile(icon, dest);
				}
				if( thumb != null && thumb.getFileSize() > 0 ){
					dest = RES_PATH + t.getThumbImage();
					logger.debug("ThumbImage path: " + dest);
					FileHelper.writeFile(thumb, dest);
				}
				boolean updateSizeFlag = true;
				if( zip != null && zip.getFileSize() > 0 ){
					if (zipfilename == null) {
						dest = RES_PATH + t.getZipfile();
						logger.debug("Zipfile path: {}", dest);
						FileHelper.writeFile(zip, dest);
					} else {
						dest = RES_PATH + zipfilename;
						String outputPath = this.genZip(zip);
						logger.debug("outputPath path: {} ", dest);
						FileHelper.writeFile(outputPath, dest);
					}
				} else if (filePath != null) {				// 2/3 指定URL copy素材
					dest = RES_PATH + t.getZipfile();
					FileHelper.writeFile(filePath, dest);
					logger.debug("copy {} to {} ", filePath, dest);
				} else {
					updateSizeFlag = false;
				}
				if (updateSizeFlag) {
					int filesize = this.getFileSize(new File(dest));
					int kb = filesize / 1024;
					logger.debug(dest + ":(HD) " + kb + " VS " + t.getBooksize());
					if (kb == 0 || kb != t.getBooksize()) {
						if (filesize == 0)
							logger.warn("{} is 0MB", dest);
						else 
							logger.warn(dest + "'s size error: HD is {}, upload is {}", kb, t.getBooksize());
						ret = -1;
					}
					int ret1 = this.commonService.executeSQL("update bookitems set booksize=? where id=?", kb, t.getId());
					logger.debug("{}:booksize update {}", t.getId(), ret1);
				}
			}
			
			
		} else if ("update".equals(op)) {
			t.setUpdate_by(userId);
			String zipfilename = null;
			if (!t.getZipfile().endsWith(".zip")) {
				zipfilename = t.getZipfile().replaceFirst("\\.(pdf|swf)$", ".zip");
				logger.debug("{} -> {}", t.getZipfile(), zipfilename);
				t.setZipfile(zipfilename);
			}
			ret = this.baseService.update(t);
			if (ret > -1 && city_id > 0) {			
				Book2City b2c = new Book2City();
				b2c.setCity_id(city_id);
				b2c.setBook_id(t.getId());
				b2c.setSale_price(t.getSale_price());
				b2c.setSubscribe_quota(t.getSubscribe_quota());
				ret = this.b2cService.update(b2c);
				if (ret < 1) logger.info("book2city update fail:{}", ret);
			} else {
				logger.info("bookitems update OK:{}", ret);
			}
			if(ret > -1){
				if(icon != null && icon.getFileSize() > 0){
					dest = RES_PATH + t.getIconImage();
					logger.debug("IconImage Path: " + dest);
					FileHelper.writeFile(icon, dest);
					if(oldIcon != null && oldIcon.length() > 0){
						dest = RES_PATH + oldIcon;
						logger.debug("delete IconImage : " + dest);
						FileHelper.deleteFile(dest);
					}
				}
				if(thumb != null && thumb.getFileSize() > 0){
					dest = RES_PATH + t.getThumbImage();
					logger.debug("ThumbImage path: " + dest);
					FileHelper.writeFile(thumb, dest);
					if(oldThumb != null && oldThumb.length() > 0){
						dest = RES_PATH + oldThumb;
						logger.debug("delete ThumbImage : " + dest);
						FileHelper.deleteFile(dest);
					}
				}
				boolean updateSizeFlag = true;
				if(zip != null && zip.getFileSize() > 0){
					if (zipfilename == null) {
						dest = RES_PATH + t.getZipfile();
						logger.debug("Zipfile path: " + dest);
						FileHelper.writeFile(zip, dest);
					} else {
						dest = RES_PATH + zipfilename;
						String outputPath = this.genZip(zip);
						logger.debug("outputPath path: {} ", dest);
						FileHelper.writeFile(outputPath, dest);
					}
				} else if (filePath != null) {				// 3/3 指定URL copy素材
					dest = RES_PATH + t.getZipfile();
					FileHelper.writeFile(filePath, dest);
					logger.debug("copy {} to {} ", filePath, dest);
				} else {
					updateSizeFlag = false;
				}
				if (updateSizeFlag) {
					int filesize = this.getFileSize(new File(dest));
					int kb = filesize / 1024;
					logger.debug(dest + ":(HD) " + kb + " VS " + t.getBooksize());
					if (kb == 0 || kb != t.getBooksize()) {
						if (filesize == 0)
							logger.warn("{} is 0MB", dest);
						else 
							logger.warn(dest + "'s size error: HD is {}, upload is {}", kb, t.getBooksize());
						ret = -1;
					}
					int ret1 = this.commonService.executeSQL("update bookitems set booksize=? where id=?", kb, t.getId());
					logger.debug("{}:booksize update {}", t.getId(), ret1);
				}
			}
		}
		if (ret > -1) {
			request.setAttribute("entryURL", entryURL.replaceFirst("\\.do$", ""));
			return mapping.findForward("success");
		}else {
			return mapping.findForward("err");
		}
	}
	
	private int getFileSize(File f) {
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(f);
			int size = fis.available();
			fis.close();
			logger.debug(f.getName() + "'s size = " + size);
			return size;
		} catch (Exception e) {
			logger.warn(f.getName() + " :" + e.getMessage());
			return 0;
		} finally {
			if (fis != null) try {fis.close(); } catch (Exception e) {}
		}
	}
	
	private ActionForward remove(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)throws Exception {
		
		BookItems t = new BookItems();
		DynaBean dynaForm = (DynaBean) form;
		try {			
			PropertyUtils.copyProperties(t, dynaForm.get("vo"));
			logger.debug(t.getId() + ":" + t.getBookname() + "/" + t.getIconImage());
		} catch (Exception e) {
			logger.warn("PropertyUtils", e);
			return mapping.findForward("err");
		}
		
		int ret = -1;
        String icon = t.getIconImage();
        String thumb = t.getThumbImage();
        String zip = t.getZipfile();
        List<String> backups = baseService.getBookItemsBackupZipById(t.getId());
        
        logger.debug("backupzip: " + backups);
        
		// file: icon, thumb, zip, backup
					
		try{
			ret = this.baseService.delete(t);
			Integer userId = (Integer) request.getSession().getAttribute("user_id");
			int city_id = this.cityPService.getCityPermission(userId, (String) request.getSession().getAttribute("funcurl"));
			if (ret > -1 && city_id > 0) {			
				Book2City b2c = new Book2City();
				b2c.setCity_id(city_id);
				b2c.setBook_id(t.getId());
				b2c.setSale_price(t.getSale_price());
				b2c.setSubscribe_quota(t.getSubscribe_quota());
				b2c.setEnable_flag(t.getEnable_flag());
				ret = this.b2cService.insert(b2c);
			}
		}catch(CdfException cex){
			MessageHandler.getInstance().processError(request, cex.getMessage());
		}			

		if (ret > -1) {
			String path;
			if(icon != null && icon.length() > 0){
				path = RES_PATH + icon;
				logger.debug("delete IconImage : " + path);
				FileHelper.deleteFile(path);
			}
			
			if(thumb != null && thumb.length() > 0){
				path = RES_PATH + thumb;
				logger.debug("delete ThumbImage : " + path);
				FileHelper.deleteFile(path);
			}
			
			if(zip != null && zip.length()> 0){
				path = RES_PATH + zip;
				logger.debug("delete zipFile : " + path);
				FileHelper.deleteFile(path);
			}
			
			if(backups != null && backups.size() > 0){
				for(String backup : backups){
					path = RES_PATH + backup;
					logger.debug("delete backupfiles : " + path);
					FileHelper.deleteFile(path);
				}
			}			
			logger.debug("delete complete");
			request.setAttribute("entryURL", entryURL.replaceFirst("\\.do$", ""));
			return mapping.findForward("success");
		}else {
			return mapping.findForward("err");
		}
	}

	public ActionForward showIcon(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		String file = request.getParameter("file");
		if(file != null && file.length()> 0){
			String path = RES_PATH + file;			
			FileHelper.writeImageToResponse(response, path);
		}
		
		return null;
	}
	
	public ActionForward showThumb(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		
		String file = request.getParameter("file");
		if(file != null && file.length()> 0){
			String path = RES_PATH + file;			
			FileHelper.writeImageToResponse(response, path);
		}
				
		return null;
	}
	
	public ActionForward zipDownload(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String id = request.getParameter("id");
		if(id != null && id.length() > 0){
			BookItems book = baseService.findSingleBookItemById(id);
			if(book != null && book.getZipfile() != null){
				String path = RES_PATH + book.getZipfile();
				FileHelper.downloadFile(response, path, book.getZipFileName());
			}
			
		}
		return null;
	}
	//QueryBookItemsInAlbum
	public ActionForward ajaxCheckBookItem(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String id = request.getParameter("id");
		if(id != null && id.length() > 0){
			// download_flag
			Map<String,Object> result = new HashMap<String,Object>(1);
			
			BookItems book = this.baseService.findById(id);
			//正在被下載
			if("Y".equals(book.getDownload_flag())){
				result.put("type", "D");				
			}else{
				
				String sqlwhere= "id in (select ALBUM_ID from book2album where BOOK_ID = ?)";
				List<BookItems> albums = this.baseService.find(sqlwhere, id);
				List<String> list = new ArrayList<String>();
				// 是否包含於合輯中
				if(albums != null && albums.size() > 0){
				    for(BookItems album: albums){
						list.add(album.getBookname());
					}	
					result.put("type", "A");
					result.put("value",list);
					
				}else{
					sqlwhere = "a.BOOK_ID = ? and a.PRODUCT_TYPE = 1";
					List<ProductID2Book> pbs = this.pbService.find(sqlwhere, book.getId());
					if(pbs != null && pbs.size() > 0){
						for(ProductID2Book pb : pbs){
							list.add(pb.getProduct_id());
						}						
					}
					result.put("type","P");
					result.put("value", list);
					
				}		
			}
			
			JSONObject json = JSONObject.fromObject(result);

			PrintWriter out=response.getWriter();
			logger.debug(json.toString());
	        out.println(json);
	        out.flush();
		}
		return null;
	}
}
